#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from generate.generator import BasicGenerator

import logging


class CyzoneProjectListGenerator(BasicGenerator):
    def gen_task(self, extra=None):
        url_format = 'https://data.cyzone.cn/company/list-0-0-0-1-{0}/0'
        page = 1
        url = url_format.format(page)
        task = {
            'type': self.name,
            'url': url,
            'url_format': url_format,
            'page': page,
        }
        length = self.mq.push(self.queue_name, json.dumps(task))
        logging.info('{0} {1}'.format(length, task))
        self.stat.incr(self.stat_hash, 'gen_task')


class CyzoneProjectGenerator(BasicGenerator):
    def get_project(self):
        sql = '''select project_id, stage, link from cyzone_project_list;'''
        rows = self.mdb.query(sql)
        dic = {}
        for row in rows:
            project_id, stage, link = row[:]
            dic[project_id] = (stage, link)
        return dic

    def gen_task(self, extra=None):
        projects = self.get_project()
        for project_id, info in projects.items():
            stage, url = info[:]
            task = {
                'type': self.name,
                'url': url,
                'project_id': project_id,
                'stage': stage
            }
            length = self.rds.rpush(self.queue_name, json.dumps(task))
            logging.info('{0} {1}'.format(length, task))
            self.stat.incr(self.stat_hash, 'gen_task')
